//============================================================================
// Name        : PatternHandler.cpp
// Author      : Anthea Neums, Jonas Halbach
//			   :
// Description : This Class splits a Pattern-String into a Parts of a specified length.
//               This Parts are safed in a Map, which stores the positions of this
//				 String part in a vector.
//============================================================================

#include "PatternHandler.h"

using namespace std;

namespace algorithm {


/**
 * The construcor of this class splits the a string-value in differnt parts of size
 * wordlength. The position of the string in the pattern is stored in a vector<int>
 * associated to this string-pattern.
 */
PatternHandler::PatternHandler(char *value, int wordLength) {

	patternMap = new HashMap();
	int len = strlen(value);

	// Iterating over the string
	for (int i = 0; i <= len - wordLength; i++) {

		//Storing the string at the actual position with the specified length.
		char *word = new char[wordLength + 1];
		strncpy(word, value + i, wordLength);
		word[wordLength] = '\0';

		HashMap::iterator it = patternMap->find(word);
		//Testing if the string is yet in the map. If yes just push the position of the
		//string to the vector associated to it. If not create a new a new vector and connect
		//it to the string
		if (it == patternMap->end()) {
			vector<int> *vec = new vector<int>();
			vec->push_back(i);
			patternMap->insert(it, make_pair<char*, vector<int> *>(word, vec));
		} else {
			it->second->push_back(i);
		}
	}
}

/**
 * Printing the content of the map. Helpfully for testing issues.
 */
void PatternHandler::printPatternMap()
{
	HashMap::iterator it = patternMap->begin();

	while(it != patternMap->end())
	{

		cout << it->first << " : " << endl;
		printVector(it->second);
		it ++;
	}
}

/**
 * Printing the content of a vector. Helpfully for testing issues.
 */
void PatternHandler::printVector(vector<int> *vec)
{
	unsigned int vec_size = vec->size();
	for(vector<int>::size_type i = 0; i < vec_size; i++)
	{
		cout << vec->at(i) << ", " << flush;
	}
	cout << std::endl;
}

/**
 * Getting the positions in the pattern associated to the string.
 * @param *string is the string, you want to get the associated positions of.
 *
 * @return a vector of positions associated to the specified string.
 */
vector<int> *PatternHandler::getPositions(char *string)
{
	HashMap::iterator position = patternMap->find(string);
	return (position == patternMap->end()) ? NULL : position->second;
}

PatternHandler::~PatternHandler() {
	patternMap->clear();
	delete patternMap;

}



} /* namespace algorithm */
